<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>第11章 全局数据管理与 Vuex | 深入理解Vue.js实战</title>
    <meta name="generator" content="VuePress 1.9.7">
    
    <meta name="description" content="作者：被删">
    
    <link rel="preload" href="/vue-ebook/assets/css/0.styles.2728a2da.css" as="style"><link rel="preload" href="/vue-ebook/assets/js/app.a856ee15.js" as="script"><link rel="preload" href="/vue-ebook/assets/js/2.2a4d101b.js" as="script"><link rel="preload" href="/vue-ebook/assets/js/3.9083e877.js" as="script"><link rel="preload" href="/vue-ebook/assets/js/10.adca14b7.js" as="script">
    <link rel="stylesheet" href="/vue-ebook/assets/css/0.styles.2728a2da.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/vue-ebook/" class="home-link router-link-active"><!----> <span class="site-name">深入理解Vue.js实战</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/vue-ebook/" class="nav-link">概述</a></div><div class="nav-item"><a href="/vue-ebook/vue-ebook/" class="nav-link router-link-active">内容</a></div> <a href="https://github.com/godbasin/vue-ebook" target="_blank" rel="noopener noreferrer" class="repo-link">
    Github
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/vue-ebook/" class="nav-link">概述</a></div><div class="nav-item"><a href="/vue-ebook/vue-ebook/" class="nav-link router-link-active">内容</a></div> <a href="https://github.com/godbasin/vue-ebook" target="_blank" rel="noopener noreferrer" class="repo-link">
    Github
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav>  <ul class="sidebar-links"><li><section class="sidebar-group depth-0" style="padding-top:;"><!----> <p class="sidebar-heading"><span>前言</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/vue-ebook/vue-ebook/0.html" class="sidebar-link">前端框架的出现</a></li></ul></section></li><li><section class="sidebar-group depth-0" style="padding-top:;"><!----> <p class="sidebar-heading"><span>第一部分 Vue快速入门</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/vue-ebook/vue-ebook/1.html" class="sidebar-link">第1章 Vue 框架介绍</a></li><li><a href="/vue-ebook/vue-ebook/2.html" class="sidebar-link">第2章 Vue 环境快速搭建</a></li><li><a href="/vue-ebook/vue-ebook/3.html" class="sidebar-link">第3章 Vue 基础介绍</a></li><li><a href="/vue-ebook/vue-ebook/4.html" class="sidebar-link">第4章 Vue 组件的使用</a></li><li><a href="/vue-ebook/vue-ebook/5.html" class="sidebar-link">第5章 常用指令和自定义指令</a></li><li><a href="/vue-ebook/vue-ebook/6.html" class="sidebar-link">第6章 Vue 动画</a></li><li><a href="/vue-ebook/vue-ebook/7.html" class="sidebar-link">第7章 Vue Router 路由搭建应用</a></li><li><a href="/vue-ebook/vue-ebook/8.html" class="sidebar-link">第8章 实战：Todo List 从组件到应用</a></li></ul></section></li><li><section class="sidebar-group depth-0" style="padding-top:10px;"><div class="kitty-main" data-v-2b653b36><span class="stand" data-v-2b653b36></span> <div class="cat" data-v-2b653b36><div class="body" data-v-2b653b36></div> <div class="head" data-v-2b653b36><div class="ear" data-v-2b653b36></div> <div class="ear" data-v-2b653b36></div></div> <div class="face" data-v-2b653b36><div class="nose" data-v-2b653b36></div> <div class="whisker-container" data-v-2b653b36><div class="whisker" data-v-2b653b36></div> <div class="whisker" data-v-2b653b36></div></div> <div class="whisker-container" data-v-2b653b36><div class="whisker" data-v-2b653b36></div> <div class="whisker" data-v-2b653b36></div></div></div> <div class="tail-container" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36></div></div></div></div></div></div></div></div></div></div> <p class="sidebar-heading open"><span>第二部分 Vue的正确使用方式</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/vue-ebook/vue-ebook/9.html" class="sidebar-link">第9章 思维转变与大型项目管理</a></li><li><a href="/vue-ebook/vue-ebook/10.html" class="sidebar-link">第10章 如何正确地进行抽象</a></li><li><a href="/vue-ebook/vue-ebook/11.html" aria-current="page" class="active sidebar-link">第11章 全局数据管理与 Vuex</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/vue-ebook/vue-ebook/11.html#_11-1-组件间通信" class="sidebar-link">11.1 组件间通信</a></li><li class="sidebar-sub-header"><a href="/vue-ebook/vue-ebook/11.html#_11-2-全局数据管理" class="sidebar-link">11.2 全局数据管理</a></li><li class="sidebar-sub-header"><a href="/vue-ebook/vue-ebook/11.html#_11-3-使用-vuex" class="sidebar-link">11.3 使用 Vuex</a></li></ul></li><li><a href="/vue-ebook/vue-ebook/12.html" class="sidebar-link">第12章 实战：三天开发一个管理端</a></li><li><a href="/vue-ebook/vue-ebook/13.html" class="sidebar-link">第13章 实战：表单配置化实现</a></li><li><a href="/vue-ebook/vue-ebook/14.html" class="sidebar-link">第14章 实战：使用 Webpack 或 Vue CLI 搭建多页应用</a></li><li><a href="/vue-ebook/vue-ebook/15.html" class="sidebar-link">第15章 Vue 周边拓展</a></li><li><a href="/vue-ebook/vue-ebook/16.html" class="sidebar-link">第16章 关于 Vue 3.0</a></li></ul></section></li><li><section class="sidebar-group depth-0" style="padding-top:;"><!----> <p class="sidebar-heading"><span>后记</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/vue-ebook/vue-ebook/99.html" class="sidebar-link">关于框架选型</a></li></ul></section></li></ul> </aside> <main class="page"> <div class="theme-default-content content__default"><h1 id="第11章-全局数据管理与-vuex"><a href="#第11章-全局数据管理与-vuex" class="header-anchor">#</a> 第11章 全局数据管理与 Vuex</h1> <blockquote><p>本章节相关代码存放在<a href="https://github.com/godbasin/vue-ebook/tree/vue-sourcecode/11" target="_blank" rel="noopener noreferrer">Github<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>中。</p></blockquote> <p>通常来说，我们刚开始一个项目的时候，项目规模都比较少。这样的情况下，我们并不会引入过于复杂的数据和状态管理工具，而随着我们项目在不断地变大、各个页面中需要共享和通信的内容越来越多，同时也加入了新成员、不同开发之间的习惯不一致，于是到后期可能会出现事件的传递、全局数据满天飞的情况。</p> <p>这样会有什么隐患呢？大概就是当我们想要改某个全局数据的时候，发现影响到了其他的页面。更让人头疼的是在测试的时候并没有发现（毕竟有在项目规模较大的情况下，回归测试的成本也会越来越重），然后触发了线上事故。</p> <p>当然，即使在这样的情况下，也并不意味着我们需要在一开始就需要使用很完善的工具库。除非是项目在最初就已经定位为较大规模，这种情况下我们需要根据预期来选型。否则项目在不断维护和壮大的过程中，我们需要不断地进行优化甚至重构，同时根据需要引进不同的工具库来进行管理。</p> <p>我们来看一下，一般全局数据要用怎样的方式来管理会比较好。</p> <h2 id="_11-1-组件间通信"><a href="#_11-1-组件间通信" class="header-anchor">#</a> 11.1 组件间通信</h2> <p>在 Vue 中，不管是页面也好，是模块或是公共组件也好，相互之间的通信几乎是必不可少的。我们先来看一下前面讲过的一些数据通信的方式。</p> <h3 id="_11-1-1-父子组件通信"><a href="#_11-1-1-父子组件通信" class="header-anchor">#</a> 11.1.1 父子组件通信</h3> <p><a href="/vue-ebook/vue-ebook/4.html">第4章</a>中，我们其实也已经简单介绍过父子组件之间的通信，一般来说会通过 Prop 从父组件往子组件传递数据，同时子组件可以通过<code>$emit()</code>把数据传递到父组件。除此之外，父组件还可以通过<code>ref</code>来引用和访问子组件。同样的，还可以使用<code>$parent</code>、<code>$children</code>、<code>$root</code>等 API 来分别获取父实例、子实例和根实例。</p> <p>那么，除了父子以外的组件要怎么处理呢？</p> <h3 id="_11-1-2-全局事件管理"><a href="#_11-1-2-全局事件管理" class="header-anchor">#</a> 11.1.2 全局事件管理</h3> <p>除了不断地使用<code>$parent</code>、<code>$children</code>、<code>$root</code>等 API 来叠加使用获取想要的实例（不推荐这样的操作，因为一旦布局调整就变得很被动了），我们可以在根实例上提供统一的事件处理，同时封装成公共库的方式来提供。这里直接使用<a href="/vue-ebook/vue-ebook/8.html">第8章</a>中 Todo List 弹窗来作为例子，通过在最外层导出根实例：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token comment">// main.js</span>
<span class="token comment">// 默认 export 该 Vue 实例</span>
<span class="token keyword">export</span> <span class="token keyword">default</span> <span class="token keyword">new</span> <span class="token class-name">Vue</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  <span class="token literal-property property">el</span><span class="token operator">:</span> <span class="token string">&quot;#app&quot;</span><span class="token punctuation">,</span>
  router<span class="token punctuation">,</span> <span class="token comment">// 传入路由能力</span>
  <span class="token function-variable function">render</span><span class="token operator">:</span> <span class="token parameter">h</span> <span class="token operator">=&gt;</span> <span class="token function">h</span><span class="token punctuation">(</span>App<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><p>然后在需要的组件或者公共函数方法里引入，同时直接使用<code>$emit</code>触发事件、<code>$on</code>监听事件：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token comment">// confirm.js</span>
<span class="token comment">// 获取该实例</span>
<span class="token keyword">import</span> vm <span class="token keyword">from</span> <span class="token string">&quot;../main&quot;</span><span class="token punctuation">;</span>
<span class="token comment">// 传入标题、内容、确认按钮和取消按钮的文案</span>
<span class="token keyword">export</span> <span class="token keyword">function</span> <span class="token function">confirmDialog</span><span class="token punctuation">(</span><span class="token parameter"><span class="token punctuation">{</span> title<span class="token punctuation">,</span> text<span class="token punctuation">,</span> cancelText<span class="token punctuation">,</span> confirmText <span class="token punctuation">}</span></span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token parameter">resolve<span class="token punctuation">,</span> reject</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
    <span class="token comment">// 把 reject 和 resolve 通过 $emit 事件传参带过去，方便进行 Promise 状态扭转</span>
    vm<span class="token punctuation">.</span><span class="token function">$emit</span><span class="token punctuation">(</span><span class="token string">&quot;setDialog&quot;</span><span class="token punctuation">,</span> <span class="token punctuation">{</span>
      title<span class="token punctuation">,</span>
      text<span class="token punctuation">,</span>
      cancelText<span class="token punctuation">,</span>
      confirmText<span class="token punctuation">,</span>
      resolve<span class="token punctuation">,</span>
      reject
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token comment">// App.vue</span>
<span class="token keyword">import</span> vm <span class="token keyword">from</span> <span class="token string">&quot;../main&quot;</span><span class="token punctuation">;</span>
<span class="token keyword">export</span> <span class="token keyword">default</span> <span class="token punctuation">{</span>
  <span class="token comment">// 其他选型省略</span>
  <span class="token function">mounted</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">$nextTick</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
      vm<span class="token punctuation">.</span><span class="token function">$on</span><span class="token punctuation">(</span><span class="token string">&quot;setDialog&quot;</span><span class="token punctuation">,</span> <span class="token parameter">dialogInfo</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
        <span class="token comment">// 将弹窗相关信息、弹窗组件添加进 component 数组中</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>items<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span><span class="token punctuation">{</span> dialogInfo<span class="token punctuation">,</span> <span class="token literal-property property">component</span><span class="token operator">:</span> ConfirmDialog <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre></div><blockquote><p><a href="https://vue-eboook-1255459943.cos.ap-chengdu.myqcloud.com/11/1-event-bus/index.html" target="_blank" rel="noopener noreferrer">点击此处查看页面效果<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> <a href="https://github.com/godbasin/vue-ebook/tree/vue-sourcecode/11/1-event-bus" target="_blank" rel="noopener noreferrer">点击此处查看源码<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></p></blockquote> <p>通过这样的方式，我们可以在每个需要的组件里，引入根实例，然后再在需要的时候分别进行事件的监听和触发就可以了。但是这个方法的缺点在本章开头也有提到，我们在新增一个事件监听和触发的时候，很容易和已有的事件名冲突，同时我们想要查看到底有哪些地方进行了某个事件的监听，也只能通过全局搜索的方式来查找，多人协作的情况下很容易出现问题。</p> <h2 id="_11-2-全局数据管理"><a href="#_11-2-全局数据管理" class="header-anchor">#</a> 11.2 全局数据管理</h2> <p>除了通过事件通知数据变更，常见的还有其他方式来管理全局数据，我们一起来看一下。</p> <h3 id="_11-2-1-数据的流动"><a href="#_11-2-1-数据的流动" class="header-anchor">#</a> 11.2.1 数据的流动</h3> <p><a href="/vue-ebook/vue-ebook/10.html">第10章</a>我们介绍了如何将应用和界面抽象成数据管理，其中说到一个应用包含了静态的模板和从外部注入的数据（见 10.2 章节）。数据在注入到我们的应用中后，并不只是简单地存在，它可能会影响应用的状态、同时也会影响其他同样注入的数据。数据与数据之间的交互，其实在某方面相等于我们组件之间的通信，包括但不限于以下的一些方式：</p> <ul><li>事件通知</li> <li>共享对象</li> <li>单方向流动</li></ul> <h4 id="事件通知"><a href="#事件通知" class="header-anchor">#</a> 事件通知</h4> <p>事件的监听和触发机制，在许多的场景下都能适用，如浏览器点击、输入框的输入操作，则是典型的事件机制。而在很多时候，我们也可以通过事件通知的方式，来进行数据间的交互，如 Websocket 机制。在 Vue 中，除了使用根实例来绑定作为事件中心，更常见的就是我们自行创建一个事件中心来进行管理：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token comment">// eventBus.js</span>
<span class="token keyword">const</span> events <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">;</span>

<span class="token keyword">function</span> <span class="token function">on</span><span class="token punctuation">(</span><span class="token parameter">eventName<span class="token punctuation">,</span> callback</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">let</span> event <span class="token operator">=</span> events<span class="token punctuation">.</span><span class="token function">find</span><span class="token punctuation">(</span><span class="token parameter">x</span> <span class="token operator">=&gt;</span> x<span class="token punctuation">.</span>eventName <span class="token operator">===</span> eventName<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>event<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">// 如果已有该事件，添加到监听者中</span>
    event<span class="token punctuation">.</span><span class="token function">addListener</span><span class="token punctuation">(</span>callback<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
    <span class="token comment">// 如果没有该事件，则添加新事件，并添加到监听者</span>
    event <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MyEvent</span><span class="token punctuation">(</span>eventName<span class="token punctuation">)</span><span class="token punctuation">;</span>
    event<span class="token punctuation">.</span><span class="token function">addListener</span><span class="token punctuation">(</span>callback<span class="token punctuation">)</span><span class="token punctuation">;</span>
    events<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span>event<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">function</span> <span class="token function">emit</span><span class="token punctuation">(</span><span class="token parameter">eventName<span class="token punctuation">,</span> <span class="token operator">...</span>params</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">let</span> event <span class="token operator">=</span> events<span class="token punctuation">.</span><span class="token function">find</span><span class="token punctuation">(</span><span class="token parameter">x</span> <span class="token operator">=&gt;</span> x<span class="token punctuation">.</span>eventName <span class="token operator">===</span> eventName<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token comment">// 如果已有该事件，则触发</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>event<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    event<span class="token punctuation">.</span><span class="token function">trigger</span><span class="token punctuation">(</span><span class="token operator">...</span>params<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">class</span> <span class="token class-name">MyEvent</span> <span class="token punctuation">{</span>
  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token parameter">eventName</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">// 创建一个事件，传入事件名</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>eventName <span class="token operator">=</span> eventName<span class="token punctuation">;</span>
    <span class="token comment">// 同时动态生成一个监听者管理</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>listeners <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  <span class="token comment">// 触发事件，传入参数</span>
  <span class="token function">trigger</span><span class="token punctuation">(</span><span class="token parameter"><span class="token operator">...</span>params</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">// 遍历监听者，触发回调</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>listeners<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token parameter">x</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
      <span class="token function">x</span><span class="token punctuation">(</span><span class="token operator">...</span>params<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  <span class="token comment">// 添加监听者</span>
  <span class="token function">addListener</span><span class="token punctuation">(</span><span class="token parameter">callback</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>listeners<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span>callback<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">export</span> <span class="token keyword">default</span> <span class="token punctuation">{</span>
  on<span class="token punctuation">,</span>
  emit
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre></div><p>同样的我们要实现前面 Todo List 的能力，只需要调整触发和监听的地方：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token comment">// confirm.js</span>
<span class="token comment">// 获取事件中心</span>
<span class="token keyword">import</span> eventBus <span class="token keyword">from</span> <span class="token string">&quot;./eventBus&quot;</span><span class="token punctuation">;</span>
<span class="token keyword">export</span> <span class="token keyword">function</span> <span class="token function">confirmDialog</span><span class="token punctuation">(</span><span class="token parameter"><span class="token punctuation">{</span> title<span class="token punctuation">,</span> text<span class="token punctuation">,</span> cancelText<span class="token punctuation">,</span> confirmText <span class="token punctuation">}</span></span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token parameter">resolve<span class="token punctuation">,</span> reject</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
    <span class="token comment">// 把 reject 和 resolve 通过 emit 事件传参带过去，方便进行 Promise 状态扭转</span>
    eventBus<span class="token punctuation">.</span><span class="token function">emit</span><span class="token punctuation">(</span><span class="token string">&quot;setDialog&quot;</span><span class="token punctuation">,</span> <span class="token punctuation">{</span>
      title<span class="token punctuation">,</span>
      text<span class="token punctuation">,</span>
      cancelText<span class="token punctuation">,</span>
      confirmText<span class="token punctuation">,</span>
      resolve<span class="token punctuation">,</span>
      reject
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token comment">// App.vue</span>
<span class="token comment">// 获取事件中心</span>
<span class="token keyword">import</span> eventBus <span class="token keyword">from</span> <span class="token string">&quot;./utils/eventBus&quot;</span><span class="token punctuation">;</span>
<span class="token keyword">export</span> <span class="token keyword">default</span> <span class="token punctuation">{</span>
  <span class="token comment">// 其他选型省略</span>
  <span class="token function">mounted</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">$nextTick</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
      eventBus<span class="token punctuation">.</span><span class="token function">on</span><span class="token punctuation">(</span><span class="token string">&quot;setDialog&quot;</span><span class="token punctuation">,</span> <span class="token parameter">dialogInfo</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
        <span class="token comment">// 将弹窗相关信息、弹窗组件添加进 component 数组中</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>items<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span><span class="token punctuation">{</span> dialogInfo<span class="token punctuation">,</span> <span class="token literal-property property">component</span><span class="token operator">:</span> ConfirmDialog <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre></div><p>事件通知机制很方便，可以随意地定义触发的时机，也可以任意地点使用监听或是触发。但前面也说过，事件机制的弊端也是很明显，就是每一个事件的触发对应一个监听，关系是一一对应。在整个应用中看，则是散落在各处，随意乱窜的数据流动。需要定位的时候，只能通过全局搜索的方式来跟踪数据的去向。</p> <p>我们来看个示例图（图 11-1），这里只有事件 1 和事件 2 的触发和监听，存在跨组件甚至跨页面的事件通知。如果在一个规模较大的应用中，可能会导致满屏的事件，同时事件之间并没有什么规律可循。这样我们每次改动事件相关的代码，例如多传一个参数、改变某个参数，都可能会导致未知的错误，需要全局搜索出相关的事件，并一一进行回归测试才可以。<br> <img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/vue-11-2.jpg" alt="image"><br>
图 11-1 事件通知通信机制</p> <p>当然，也有些人会定义一个中转站，所有的事件数据流都会经过那，这样的维护方式会有所改善。</p> <p><img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/vue-11-3.jpg" alt="imgae"><br>
图 11-2 事件通知增加中转站</p> <p>类似这种，所有的数据流都可以在中转站找到，所有的数据都会储存在这里，数据的更新也必会经过这里。这样我们在新增一个事件的时候，就不会担心和已有的事件名冲突，同时也可以使用 Typescript 来定义每个事件的参数类型，就可以稍微避免一些改动引起不必要的错误了。</p> <h4 id="共享对象"><a href="#共享对象" class="header-anchor">#</a> 共享对象</h4> <p>共享对象是很简单的一种方式，当我们需要多个地方使用相同的数据，我们就把它们放置在一个地方，大家都去那理获取和更新。</p> <p><img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/vue-11-4.jpg" alt="imgae"><br>
图 11-3 共享对象通信机制</p> <p>常见的方式是，我们可以简单的使用一个叫<code>globalData.js</code>的文件来管理全局用的数据，文件共享的方式，其实和前面说到的共享对象的方式比较相似：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token comment">// globalData.js</span>
<span class="token comment">// globalData 用来存全局数据</span>
<span class="token keyword">let</span> globalData <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">;</span>

<span class="token comment">// 获取全局数据</span>
<span class="token comment">// 传 key 获取对应的值</span>
<span class="token comment">// 不传 key 获取全部值</span>
<span class="token keyword">export</span> <span class="token keyword">function</span> <span class="token function">getGlobalData</span><span class="token punctuation">(</span><span class="token parameter">key</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">return</span> key <span class="token operator">?</span> globalData<span class="token punctuation">[</span>key<span class="token punctuation">]</span> <span class="token operator">:</span> globalData<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token comment">// 设置全局数据</span>
<span class="token keyword">export</span> <span class="token keyword">function</span> <span class="token function">setGlobalData</span><span class="token punctuation">(</span><span class="token parameter">key<span class="token punctuation">,</span> value</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// 需要传键值对</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>key <span class="token operator">===</span> <span class="token keyword">undefined</span> <span class="token operator">||</span> value <span class="token operator">===</span> <span class="token keyword">undefined</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  globalData <span class="token operator">=</span> <span class="token punctuation">{</span> <span class="token operator">...</span>globalData<span class="token punctuation">,</span> <span class="token punctuation">[</span>key<span class="token punctuation">]</span><span class="token operator">:</span> value <span class="token punctuation">}</span><span class="token punctuation">;</span>
  <span class="token keyword">return</span> globalData<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token comment">// 清除全局数据</span>
<span class="token comment">// 传 key 清除对应的值</span>
<span class="token comment">// 不传 key 清除全部值</span>
<span class="token keyword">export</span> <span class="token keyword">function</span> <span class="token function">clearGlobalData</span><span class="token punctuation">(</span><span class="token parameter">key</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// 需要传键值对</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>key <span class="token operator">===</span> <span class="token keyword">undefined</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    globalData <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
    <span class="token keyword">delete</span> globalData<span class="token punctuation">[</span>key<span class="token punctuation">]</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  <span class="token keyword">return</span> globalData<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div><p>使用这种方式的全局数据，是会在页面刷新之后丢失的。如果像用户的登录态信息这种需要缓存的，更好的方式是存到 cookie 或者缓存里。</p> <p>通过注入对象的引用，来在不同组件中获取相同的数据源。在服务端开发的时候使用这样的方式，需要考虑锁的问题，当然单线程的 JS 里面这样的情况比较少，几乎可以不考虑。同时，很多时候我们定义了一个对象，某些地方想要共享这个对象包括它的状态数据，有些地方又想要获取一个全新初始化的对象。这种情况下，我们需要考虑怎样去维护一套这种数据与实例。</p> <h4 id="单方向流动"><a href="#单方向流动" class="header-anchor">#</a> 单方向流动</h4> <p>在全局数据的使用变频繁之后，我们在定位问题的时候还会遇到不知道这个数据为何改变的情况，因为所有引用到这个全局数据的地方都可能对它进行改变。这种情况下，给数据的流动一个方向，则可以方便地跟踪数据的来源和去处。通过流的方式来管理状态，常见的状态管理工具像 Vuex、Redux 等，都是这样管理的。</p> <p><img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/vue-11-5.jpg" alt="imgae"><br>
图 11-4 单方向流动通信机制</p> <p>当然，赋予数据流方向，但是数据的存放呢，可以通过共享对象的方式，也可以维护一个数据中心。所有的数据变更方式、触发逻辑、影响范围，都在数据中心里面管理和维护。后面我们会介绍 Vuex，所以这里先不过多讲解单方向流动的数据管理实现。</p> <h4 id="树状作用域"><a href="#树状作用域" class="header-anchor">#</a> 树状作用域</h4> <p>很多时候，我们的应用通过一层层地封装和隔离，最终会呈现为树状。我们可以根据组件的树状作用域，结合共享对象的管理，来注入树状的数据结构。典型如 Angular 里，则是通过提供通用的依赖注入方式，配合树状的模块管理，可通过局部注入实例来获取共享或是隔离的数据。当然，这样的做法在其他框架中并不常见，而 Vue 中使用的更多是平级的单向数据流动，毕竟在 Angular 中树状结构的出现部分是为了优化脏检查机制，Vue 中我们只需要将数据变动更新到界面中就可以了。</p> <h2 id="_11-3-使用-vuex"><a href="#_11-3-使用-vuex" class="header-anchor">#</a> 11.3 使用 Vuex</h2> <p>前面我们讲到，在 Vue 组件中是通过<code>prop</code>属性和自定义事件<code>$on</code>、<code>$emit</code>可以实现父子组件间的通信。但很多时候我们的数据是需要跨组件、甚至跨页面进行共享，这种情况下我们需要更好的方式来维护这些全局的数据。我们已经讲了关于全局数据状态管理的一些常用方法，各种方式的优势和缺点也都有说到，这里我们就直接介绍 Vuex。</p> <p>Vuex 是官方推荐的状态管理工具，通过单向数据流的方式来维护状态变更。所有的数据都会存到 Store 里，只能通过提交 Mutation 或者触发 Action 的方式来改变数据，在这个过程中就会形成一个单向流动：<code>(Action) -&gt; Mutation -&gt; Store -&gt; update view</code>。关于什么是 Mutation 和 Action，什么又是 Store，可以参考下官方的配图，后面会有详细介绍：</p> <p><img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/vue-11-6.png" alt="imgae"><br>
图 11-5 Vuex 状态更新</p> <p>关于 Vuex 的用途，可以理解一下官方描述：它采用集中式存储管理应用的所有组件的状态，并以相应的规则保证状态以一种可预测的方式发生变化。</p> <h3 id="_11-3-1-vuex-核心概念"><a href="#_11-3-1-vuex-核心概念" class="header-anchor">#</a> 11.3.1 Vuex 核心概念</h3> <p>关于 Vuex，有一些基本的核心概念需要先理解一下。</p> <h4 id="state"><a href="#state" class="header-anchor">#</a> State</h4> <p>State 为状态，我们可以理解为上一章内容中抽象的数据。Vuex 中的 State，也可以理解为一个绑定到界面或组件的状态变量，就像是<code>data</code>中的变量一样：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">new</span> <span class="token class-name">Vue</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  <span class="token comment">// state</span>
  <span class="token function">data</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token punctuation">{</span>
      <span class="token literal-property property">count</span><span class="token operator">:</span> <span class="token number">0</span>
    <span class="token punctuation">}</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><p>而在 Vuex 中，State 通常是指全局的应用状态。因为 Vuex 使用单一状态树，用一个对象就包含了全部的应用层级状态。这样所有 State 的集合，就是 Store。</p> <h4 id="store"><a href="#store" class="header-anchor">#</a> Store</h4> <p>每一个 Vuex 应用的核心就是仓库(Store)，它包含着我们应用中大部分的状态(State)。状态也是数据的一种，相比直接展示在页面中的内容，状态更多时候是控制展示方式和逻辑的一些数据。像我们常说的用户登录态、地理位置等，一般来说我们存到 Store 中的数据，大多数都是需要多组件、多页面或是整个应用中共享的数据。</p> <p>一个简单的 Store 是怎样注入到我们的应用中的呢，我们来看一下：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token comment">// 引入Vuex库</span>
Vue<span class="token punctuation">.</span><span class="token function">use</span><span class="token punctuation">(</span>Vuex<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 创建一个Store</span>
<span class="token keyword">const</span> store <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Vuex<span class="token punctuation">.</span>Store</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  <span class="token comment">// 设置状态</span>
  <span class="token literal-property property">state</span><span class="token operator">:</span> <span class="token punctuation">{</span>
    <span class="token literal-property property">count</span><span class="token operator">:</span> <span class="token number">0</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
  <span class="token comment">// Mutation用于更新状态</span>
  <span class="token literal-property property">mutations</span><span class="token operator">:</span> <span class="token punctuation">{</span>
    <span class="token function">increment</span><span class="token punctuation">(</span><span class="token parameter">state</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      state<span class="token punctuation">.</span>count<span class="token operator">++</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// Vuex通过Store选项，提供了一种机制将状态从根组件“注入”到每一个子组件中（需调用 ）：</span>
<span class="token keyword">const</span> app <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Vue</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  <span class="token comment">// 其他选项省略</span>
  <span class="token comment">// 把store对象提供给“store”选项，这可以把store的实例注入所有的子组件</span>
  store
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><p>当然，我们也可以通过创建单文件或是全局对象的方式来维护这些全局的状态。但这样的方式中，数据的变化不能得到监听，需要使用方自行地去获取。我们还可以使用事件、<code>getter/setter</code>的方式来进行，但依然存在一个问题，数据的变化无法直接更新到组件和页面中。所以就有了 Vuex，使用 Vuex 我们可以获得以下效果：<br>
(1) 当 Vue 组件从 Store 中读取状态的时候，若 Store 中的状态发生变化，那么相应的组件也会相应地得到高效更新。<br>
(2) 改变 Store 中的状态只能通过 Action 或者 Mutation，这样使得我们可以方便地跟踪每一个状态的变化，来定位具体问题。</p> <p>每个应用将仅仅包含一个 Store 实例，单一状态树让我们能够直接地定位任一特定的状态片段，在调试的过程中也能轻易地取得整个当前应用状态的快照。但如果每个应用只包含了一个 Store，我们要怎样避免在不断引入全局状态的时候，避免 Store 变得臃肿呢？</p> <h4 id="module"><a href="#module" class="header-anchor">#</a> Module</h4> <p>为了解决应用变得复杂时 Store 难以维护，Vuex 允许我们将 Store 分割成模块 Module。每个模块拥有自己的 State、Mutation、Action 等，其实相当于我们将一个 Store 单一对象分成多个对象来维护，但最终也会合并为一个来进行更新，这样即使是多个模块也能够对同一 Mutation 或 Action 作出响应。</p> <p>那如果我们在不同的页面中，有相同的一些状态命名发生了冲突，要如何解决呢？我们还可以通过添加<code>namespaced: true</code>的方式，来创建带命名空间的模块，同时 Module 还支持嵌套使用：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">const</span> store <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Vuex<span class="token punctuation">.</span>Store</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  <span class="token literal-property property">modules</span><span class="token operator">:</span> <span class="token punctuation">{</span>
    <span class="token literal-property property">account</span><span class="token operator">:</span> <span class="token punctuation">{</span>
      <span class="token literal-property property">namespaced</span><span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span> <span class="token comment">// 带命名空间</span>
      <span class="token comment">// 模块内容（module assets）</span>
      <span class="token literal-property property">state</span><span class="token operator">:</span> <span class="token punctuation">{</span> <span class="token operator">...</span> <span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token comment">// 模块内的状态已经是嵌套的了，使用namespaced属性不会对其产生影响</span>
      <span class="token comment">// 可以拥有自己的Action和Mutation</span>
      <span class="token literal-property property">actions</span><span class="token operator">:</span> <span class="token punctuation">{</span>
        <span class="token function">login</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token operator">...</span> <span class="token punctuation">}</span> <span class="token comment">// -&gt; dispatch('account/login')</span>
      <span class="token punctuation">}</span><span class="token punctuation">,</span>
      <span class="token literal-property property">mutations</span><span class="token operator">:</span> <span class="token punctuation">{</span>
        <span class="token function">login</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token operator">...</span> <span class="token punctuation">}</span> <span class="token comment">// -&gt; commit('account/login')</span>
      <span class="token punctuation">}</span><span class="token punctuation">,</span>
      <span class="token comment">// 嵌套模块</span>
      <span class="token literal-property property">modules</span><span class="token operator">:</span> <span class="token punctuation">{</span>
        <span class="token comment">// 继承父模块的命名空间</span>
        <span class="token literal-property property">myPage</span><span class="token operator">:</span> <span class="token punctuation">{</span>
          <span class="token literal-property property">state</span><span class="token operator">:</span> <span class="token punctuation">{</span> <span class="token operator">...</span> <span class="token punctuation">}</span>
        <span class="token punctuation">}</span><span class="token punctuation">,</span>
        <span class="token comment">// 进一步嵌套命名空间</span>
        <span class="token literal-property property">posts</span><span class="token operator">:</span> <span class="token punctuation">{</span>
          <span class="token literal-property property">namespaced</span><span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
          <span class="token literal-property property">state</span><span class="token operator">:</span> <span class="token punctuation">{</span> <span class="token operator">...</span> <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre></div><h4 id="mutation"><a href="#mutation" class="header-anchor">#</a> Mutation</h4> <p>前面在 Store 的代码示例中也有出现过 Mutation，我们也说过，数据流的单向流动可以让开发者掌握所有数据状态的变更来源和去向。而 Mutation 的作用类似于一个守卫，所有的状态变更都必须来自 Mutation：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">const</span> store <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Vuex<span class="token punctuation">.</span>Store</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  <span class="token literal-property property">state</span><span class="token operator">:</span> <span class="token punctuation">{</span>
    <span class="token literal-property property">count</span><span class="token operator">:</span> <span class="token number">1</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
  <span class="token literal-property property">mutations</span><span class="token operator">:</span> <span class="token punctuation">{</span>
    <span class="token comment">// 每个 Mutation 都有一个字符串的事件类型 type 和一个回调函数 handler</span>
    <span class="token comment">// 这个回调函数就是我们实际进行状态更改的地方</span>
    <span class="token function">increment</span><span class="token punctuation">(</span><span class="token parameter">state</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment">// 变更状态</span>
      state<span class="token punctuation">.</span>count<span class="token operator">++</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 要调用 Mutation handler，你需要以相应的 type 调用 store.commit 方法</span>
store<span class="token punctuation">.</span><span class="token function">commit</span><span class="token punctuation">(</span><span class="token string">&quot;increment&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><p>也就是说，在 Vuex 中状态的变更只能通过提交 Mutation 来更新状态，而提交 Mutation 也只能通过 commit 对应的的事件 type 来进行。在 Vuex 中，Mutation 都是同步函数，如果是异步的话，我们的状态变更就不实时，这会影响后续其他地方获取状态的实时性。那如果我们需要异步操作，例如从后台接口拉取的数据更新，这种情况下我们可以使用 Action。</p> <h4 id="action"><a href="#action" class="header-anchor">#</a> Action</h4> <p>相比与 Mutation，Action 的不同之处在于：<br>
(1) Action 提交的是 Mutation，而不是直接变更状态。<br>
(2) Action 可以包含任意异步操作。</p> <p>我们来看一下 Action 的使用：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">const</span> store <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Vuex<span class="token punctuation">.</span>Store</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  <span class="token literal-property property">state</span><span class="token operator">:</span> <span class="token punctuation">{</span>
    <span class="token literal-property property">count</span><span class="token operator">:</span> <span class="token number">0</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
  <span class="token literal-property property">mutations</span><span class="token operator">:</span> <span class="token punctuation">{</span>
    <span class="token function">increment</span><span class="token punctuation">(</span><span class="token parameter">state</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      state<span class="token punctuation">.</span>count<span class="token operator">++</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
  <span class="token literal-property property">actions</span><span class="token operator">:</span> <span class="token punctuation">{</span>
    <span class="token comment">// Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象</span>
    <span class="token function">increment</span><span class="token punctuation">(</span><span class="token parameter">context</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment">// 因此可以调用 context.commit 提交一个 mutation</span>
      context<span class="token punctuation">.</span><span class="token function">commit</span><span class="token punctuation">(</span><span class="token string">&quot;increment&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token comment">// 其他的，也可以通过 context.state 来获取 state</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><p>关于 Vuex，还有 Getter 等概念，Getter 类似于 computed 之类的，Getter 的返回值会根据它的依赖被缓存起来，且只有当它的依赖值发生了改变才会被重新计算。这里就不过多讲解，大家可以去官网上补充更多的内容，我们来讲一些实战的用法吧。</p> <h3 id="_11-3-2-vuex-使用"><a href="#_11-3-2-vuex-使用" class="header-anchor">#</a> 11.3.2 Vuex 使用</h3> <p>Vuex 使用单一状态树，即用一个对象就包含了全部的应用层级状态。Vuex 主要在什么时候用呢？当我们一些数据需要共享的时候，例如用户信息，可能会在多个组件中使用到的。一些 ajax 请求的数据，可通过 Action 来触发请求，完成后更新到 State，页面可直接更新。至于 Vuex 的使用方式和管理模式多种多样，如：<br>
(1) 根据 Vuex 的核心概念分文件管理，像把所有的 Action 放一起管理、Mutation 放一起。<br>
(2) 根据业务功能分文件管理，相似业务数据维护在一个 Store 中。</p> <h4 id="全局弹窗-vuex-实现"><a href="#全局弹窗-vuex-实现" class="header-anchor">#</a> 全局弹窗 Vuex 实现</h4> <p>前面在<a href="/vue-ebook/vue-ebook/8.html">第8章</a>的时候，我们使用了在根实例上注册事件监听和触发的方式来实现全局弹窗，在本章介绍 Event Bus 的时候，也使用自制的事件管理来实现全局弹窗。现在，我们来使用 Vuex 重新实现一遍吧。</p> <p><strong>(1) 设计弹窗 Store。</strong></p> <p>为了实现每次调用<code>confirmDialog</code>事件的时候，都新增一个弹窗，我们可以使用一个弹窗列表的方式来管理：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token comment">// dialogStore.js</span>
<span class="token keyword">import</span> Vue <span class="token keyword">from</span> <span class="token string">&quot;vue&quot;</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> Vuex <span class="token keyword">from</span> <span class="token string">&quot;vuex&quot;</span><span class="token punctuation">;</span>
Vue<span class="token punctuation">.</span><span class="token function">use</span><span class="token punctuation">(</span>Vuex<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">const</span> dialogStore <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Vuex<span class="token punctuation">.</span>Store</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  <span class="token literal-property property">state</span><span class="token operator">:</span> <span class="token punctuation">{</span>
    <span class="token comment">// 弹窗列表，用来保存可能弹窗的一系列弹窗</span>
    <span class="token literal-property property">dialogList</span><span class="token operator">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
  <span class="token literal-property property">mutations</span><span class="token operator">:</span> <span class="token punctuation">{</span>
    <span class="token function">removeDialog</span><span class="token punctuation">(</span><span class="token parameter">state<span class="token punctuation">,</span> index</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment">// 移除弹窗</span>
      state<span class="token punctuation">.</span>dialogList<span class="token punctuation">.</span><span class="token function">splice</span><span class="token punctuation">(</span>index<span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token function">setDialog</span><span class="token punctuation">(</span>
      <span class="token parameter">state<span class="token punctuation">,</span>
      <span class="token punctuation">{</span> title<span class="token punctuation">,</span> text<span class="token punctuation">,</span> cancelText<span class="token punctuation">,</span> confirmText<span class="token punctuation">,</span> resolve<span class="token punctuation">,</span> reject <span class="token punctuation">}</span></span>
    <span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment">// 添加新的弹窗</span>
      state<span class="token punctuation">.</span>dialogList<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
        title<span class="token punctuation">,</span>
        text<span class="token punctuation">,</span>
        cancelText<span class="token punctuation">,</span>
        confirmText<span class="token punctuation">,</span>
        resolve<span class="token punctuation">,</span>
        reject
      <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">export</span> <span class="token keyword">default</span> dialogStore<span class="token punctuation">;</span>
</code></pre></div><p><strong>(2) 新增弹窗的方法。</strong></p> <p>我们需要实现一个用来添加弹窗确认的方法，同时返回一个 Promise，当用户进行了操作之后，就更新 Promise 的状态：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token comment">// confirm.js</span>
<span class="token keyword">import</span> dialogStore <span class="token keyword">from</span> <span class="token string">&quot;../components/ConfirmDialog/dialogStore&quot;</span><span class="token punctuation">;</span>

<span class="token comment">// 传入标题、内容、确认按钮和取消按钮的文案</span>
<span class="token keyword">export</span> <span class="token keyword">function</span> <span class="token function">confirmDialog</span><span class="token punctuation">(</span><span class="token parameter"><span class="token punctuation">{</span> title<span class="token punctuation">,</span> text<span class="token punctuation">,</span> cancelText<span class="token punctuation">,</span> confirmText <span class="token punctuation">}</span></span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token parameter">resolve<span class="token punctuation">,</span> reject</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
    <span class="token comment">// 调用 dialogStore.commit 提交 setDialog</span>
    <span class="token comment">// 把 reject 和 resolve 通过事件传参带过去，方便进行 Promise 状态扭转</span>
    dialogStore<span class="token punctuation">.</span><span class="token function">commit</span><span class="token punctuation">(</span><span class="token string">&quot;setDialog&quot;</span><span class="token punctuation">,</span> <span class="token punctuation">{</span>
      title<span class="token punctuation">,</span>
      text<span class="token punctuation">,</span>
      cancelText<span class="token punctuation">,</span>
      confirmText<span class="token punctuation">,</span>
      resolve<span class="token punctuation">,</span>
      reject
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">export</span> <span class="token keyword">default</span> confirmDialog<span class="token punctuation">;</span>
</code></pre></div><p><strong>(3) 使用动态组件添加。</strong></p> <p>和<a href="/vue-ebook/vue-ebook/8.html">第8章</a>一样，我们可以使用动态组件的方式，来支持同时多个弹窗的交互确认：</p> <div class="language-html extra-class"><pre class="language-html"><code><span class="token comment">&lt;!-- App.vue --&gt;</span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>template</span><span class="token punctuation">&gt;</span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span><span class="token punctuation">&gt;</span></span>
    <span class="token comment">&lt;!-- 使用 &lt;router-view&gt;&lt;/router-view&gt; 来渲染最高级路由匹配到的组件 --&gt;</span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>router-view</span><span class="token punctuation">&gt;</span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>router-view</span><span class="token punctuation">&gt;</span></span>
    <span class="token comment">&lt;!-- 动态组件由 vm 实例的 component 控制 --&gt;</span>
    <span class="token comment">&lt;!-- done 事件绑定用户操作完毕 --&gt;</span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>component</span>
      <span class="token attr-name">v-for</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>(dialogInfo, index) in dialogList<span class="token punctuation">&quot;</span></span>
      <span class="token attr-name">:key</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>index<span class="token punctuation">&quot;</span></span>
      <span class="token attr-name">:is</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>ConfirmDialog<span class="token punctuation">&quot;</span></span>
      <span class="token attr-name">:dialogInfo</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>dialogInfo<span class="token punctuation">&quot;</span></span>
      <span class="token attr-name">:index</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>index<span class="token punctuation">&quot;</span></span>
    <span class="token punctuation">&gt;</span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>component</span><span class="token punctuation">&gt;</span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">&gt;</span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>template</span><span class="token punctuation">&gt;</span></span>

<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>script</span><span class="token punctuation">&gt;</span></span><span class="token script"><span class="token language-javascript">
  <span class="token comment">// 弹窗组件</span>
  <span class="token keyword">import</span> ConfirmDialog <span class="token keyword">from</span> <span class="token string">&quot;./components/ConfirmDialog/ConfirmDialog.vue&quot;</span><span class="token punctuation">;</span>
  <span class="token keyword">import</span> dialogStore <span class="token keyword">from</span> <span class="token string">&quot;./components/ConfirmDialog/dialogStore&quot;</span><span class="token punctuation">;</span>

  <span class="token keyword">export</span> <span class="token keyword">default</span> <span class="token punctuation">{</span>
    <span class="token literal-property property">name</span><span class="token operator">:</span> <span class="token string">&quot;app&quot;</span><span class="token punctuation">,</span>
    <span class="token literal-property property">computed</span><span class="token operator">:</span> <span class="token punctuation">{</span>
      <span class="token function">dialogList</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">// 绑定 dialogStore 的 dialogList 列表</span>
        <span class="token keyword">return</span> dialogStore<span class="token punctuation">.</span>state<span class="token punctuation">.</span>dialogList<span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token function">data</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">return</span> <span class="token punctuation">{</span>
        <span class="token comment">// 用来绑定 component</span>
        ConfirmDialog
      <span class="token punctuation">}</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span><span class="token punctuation">;</span>
</span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>script</span><span class="token punctuation">&gt;</span></span>
</code></pre></div><p><strong>(4) 弹窗数据绑定。</strong></p> <p>因为通过列表的方式来管理弹窗的 Store，同时我们在动态组件中使用 Prop 的方式传入弹窗的信息，所以我们可以从 Prop 中获取到弹窗的内容：</p> <div class="language-html extra-class"><pre class="language-html"><code><span class="token comment">&lt;!-- ConfirmDialog.vue --&gt;</span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>template</span><span class="token punctuation">&gt;</span></span>
  <span class="token comment">&lt;!-- 强制出现 display: block --&gt;</span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>modal<span class="token punctuation">&quot;</span></span> <span class="token attr-name">tabindex</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>-1<span class="token punctuation">&quot;</span></span> <span class="token attr-name">role</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>dialog<span class="token punctuation">&quot;</span></span> <span class="token special-attr"><span class="token attr-name">style</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span><span class="token value css language-css"><span class="token property">display</span><span class="token punctuation">:</span> block</span><span class="token punctuation">&quot;</span></span></span><span class="token punctuation">&gt;</span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>modal-dialog<span class="token punctuation">&quot;</span></span> <span class="token attr-name">role</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>document<span class="token punctuation">&quot;</span></span><span class="token punctuation">&gt;</span></span>
      <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>modal-content<span class="token punctuation">&quot;</span></span><span class="token punctuation">&gt;</span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>modal-header<span class="token punctuation">&quot;</span></span><span class="token punctuation">&gt;</span></span>
          <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>button</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>button<span class="token punctuation">&quot;</span></span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>close<span class="token punctuation">&quot;</span></span> <span class="token attr-name">aria-label</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>Close<span class="token punctuation">&quot;</span></span><span class="token punctuation">&gt;</span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>span</span> <span class="token attr-name">aria-hidden</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>true<span class="token punctuation">&quot;</span></span><span class="token punctuation">&gt;</span></span><span class="token entity named-entity" title="&amp;times;">&amp;times;</span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>span</span><span class="token punctuation">&gt;</span></span>
          <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>button</span><span class="token punctuation">&gt;</span></span>
          <span class="token comment">&lt;!-- 弹窗标题 --&gt;</span>
          <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>h4</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>modal-title<span class="token punctuation">&quot;</span></span><span class="token punctuation">&gt;</span></span>{{dialogInfo.title || '提示'}}<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>h4</span><span class="token punctuation">&gt;</span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">&gt;</span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>modal-body<span class="token punctuation">&quot;</span></span><span class="token punctuation">&gt;</span></span>
          <span class="token comment">&lt;!-- 弹窗内容 --&gt;</span>
          <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>p</span><span class="token punctuation">&gt;</span></span>{{dialogInfo.text}}<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>p</span><span class="token punctuation">&gt;</span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">&gt;</span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>modal-footer<span class="token punctuation">&quot;</span></span><span class="token punctuation">&gt;</span></span>
          <span class="token comment">&lt;!-- 取消按钮，点击取消，cancelText 可设置按钮文案 --&gt;</span>
          <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>button</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>button<span class="token punctuation">&quot;</span></span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>btn btn-default<span class="token punctuation">&quot;</span></span> <span class="token attr-name">@click</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>cancel()<span class="token punctuation">&quot;</span></span><span class="token punctuation">&gt;</span></span>
            {{dialogInfo.cancelText || '取消'}}
          <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>button</span><span class="token punctuation">&gt;</span></span>
          <span class="token comment">&lt;!-- 确认按钮，点击确认，confirmText 可设置按钮文案 --&gt;</span>
          <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>button</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>button<span class="token punctuation">&quot;</span></span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>btn btn-primary<span class="token punctuation">&quot;</span></span> <span class="token attr-name">@click</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>confirm()<span class="token punctuation">&quot;</span></span><span class="token punctuation">&gt;</span></span>
            {{dialogInfo.confirmText || '确认'}}
          <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>button</span><span class="token punctuation">&gt;</span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">&gt;</span></span>
      <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">&gt;</span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">&gt;</span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">&gt;</span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>template</span><span class="token punctuation">&gt;</span></span>

<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>script</span><span class="token punctuation">&gt;</span></span><span class="token script"><span class="token language-javascript">
  <span class="token keyword">import</span> dialogStore <span class="token keyword">from</span> <span class="token string">&quot;./dialogStore&quot;</span><span class="token punctuation">;</span>

  <span class="token keyword">export</span> <span class="token keyword">default</span> <span class="token punctuation">{</span>
    <span class="token literal-property property">props</span><span class="token operator">:</span> <span class="token punctuation">{</span>
      <span class="token comment">// 弹窗相关信息</span>
      <span class="token literal-property property">dialogInfo</span><span class="token operator">:</span> <span class="token punctuation">{</span>
        <span class="token literal-property property">type</span><span class="token operator">:</span> Object<span class="token punctuation">,</span>
        <span class="token function-variable function">default</span><span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
      <span class="token punctuation">}</span><span class="token punctuation">,</span>
      <span class="token comment">// 弹窗的序号，移除的时候需要</span>
      <span class="token literal-property property">index</span><span class="token operator">:</span> <span class="token punctuation">{</span>
        <span class="token literal-property property">type</span><span class="token operator">:</span> Number
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token literal-property property">methods</span><span class="token operator">:</span> <span class="token punctuation">{</span>
      <span class="token comment">// 点击取消</span>
      <span class="token function">cancel</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">// 要先判断下 reject 方法在不在</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>dialogInfo<span class="token punctuation">.</span>reject<span class="token punctuation">)</span> <span class="token punctuation">{</span>
          <span class="token comment">// 取消就 reject 掉呀</span>
          <span class="token keyword">this</span><span class="token punctuation">.</span>dialogInfo<span class="token punctuation">.</span><span class="token function">reject</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
          <span class="token comment">// 移除掉这个弹窗</span>
          dialogStore<span class="token punctuation">.</span><span class="token function">commit</span><span class="token punctuation">(</span><span class="token string">&quot;removeDialog&quot;</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>index<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
      <span class="token punctuation">}</span><span class="token punctuation">,</span>
      <span class="token comment">// 点击确认</span>
      <span class="token function">confirm</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">// 要先判断下 resolve 方法在不在</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>dialogInfo<span class="token punctuation">.</span>resolve<span class="token punctuation">)</span> <span class="token punctuation">{</span>
          <span class="token comment">// 确认就 resolve 掉</span>
          <span class="token keyword">this</span><span class="token punctuation">.</span>dialogInfo<span class="token punctuation">.</span><span class="token function">resolve</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
          <span class="token comment">// 移除掉这个弹窗</span>
          dialogStore<span class="token punctuation">.</span><span class="token function">commit</span><span class="token punctuation">(</span><span class="token string">&quot;removeDialog&quot;</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>index<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span><span class="token punctuation">;</span>
</span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>script</span><span class="token punctuation">&gt;</span></span>
</code></pre></div><p><strong>(5) 弹窗确认。</strong></p> <p>最后，我们就可以使用<code>confirmDialog</code>方法来进行弹窗确认：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token comment">// 传入弹窗的内容，并通过 then 和 catch 来获取用户的操作，以便继续后续的逻辑处理</span>
<span class="token function">confirmDialog</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  <span class="token literal-property property">text</span><span class="token operator">:</span> <span class="token string">&quot;确认要删除吗？&quot;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
  <span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token parameter">res</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
    <span class="token comment">// 用户点击确认</span>
    <span class="token comment">// 二次弹窗确认</span>
    <span class="token function">confirmDialog</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
      <span class="token literal-property property">text</span><span class="token operator">:</span> <span class="token string">&quot;真的确认要删除吗？&quot;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token parameter">res</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
        <span class="token comment">// 用户点击确认</span>
      <span class="token punctuation">}</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">catch</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
        <span class="token comment">// 用户点击取消</span>
      <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span>
  <span class="token punctuation">.</span><span class="token function">catch</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
    <span class="token comment">// 用户点击取消</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><p>通过这种方式，我们可以进行二次弹窗，也可以进行多个弹窗叠加。同时使用 Promise 的方式，也可以更有连贯性地编写代码。</p> <blockquote><p><a href="https://vue-eboook-1255459943.cos.ap-chengdu.myqcloud.com/11/2-vuex-demo/index.html" target="_blank" rel="noopener noreferrer">点击此处查看页面效果<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> <a href="https://github.com/godbasin/vue-ebook/tree/vue-sourcecode/11/2-vuex-demo" target="_blank" rel="noopener noreferrer">点击此处查看源码<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></p></blockquote> <p>关于 Vuex，还有更多的使用方式，这里只是展示了绑定弹窗的一个使用方式。而在大型项目的管理中，除了将 Store 模块化，我们还可以根据需要来对 Action 和 Mutation 进行管理。除此之外，我们也还是可以自行开发全局数据、事件管理等方式来进行。但为了避免多人协作的一些问题，一般我们在选型的时候，更多会考虑规范性和维护性，所以选用官方提供的一些库也是很好的选择。</p></div> <!----> <footer class="page-edit"><div class="edit-link"><a href="https://github.com/godbasin/vue-ebook/edit/ebook-sourcecode/docs/vue-ebook/11.md" target="_blank" rel="noopener noreferrer">帮阿猪改善此页面！</a> <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></div> <!----> <div style="margin-top:30px;"><div class="el-row" style="margin-left:-10px;margin-right:-10px;"><div class="el-col el-col-24 el-col-sm-0 el-col-md-2 el-col-lg-4" style="padding-left:10px;padding-right:10px;display:block;"><div style="width:1px;height:1px;"></div></div> <div class="el-col el-col-24 el-col-sm-24 el-col-md-18 el-col-lg-16" style="padding-left:10px;padding-right:10px;"><div class="el-card box-card is-always-shadow"><div class="el-card__header"><div class="clearfix"><span>温馨提示喵</span></div></div><div class="el-card__body"> <div class="el-row" style="margin-left:-10px;margin-right:-10px;"><div class="el-col el-col-24 el-col-xs-24 el-col-sm-12" style="padding-left:10px;padding-right:10px;"><div class="el-image"><div class="image-slot"><img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/assets/img/loading.gif" style="width:100%;"></div><!----></div></div> <div class="el-col el-col-24 el-col-xs-24 el-col-sm-12" style="padding-left:10px;padding-right:10px;"><div class="copyright-text"><div>本书采用“保持署名—非商用”<a href="http://creativecommons.org/licenses/by-nc/4.0/" target="_blank">创意共享4.0许可证</a>。只要保持原作者署名和非商用，您可以自由地阅读、分享、修改本书。</div> <div>作者：<a href="https://github.com/godbasin" target="_blank">被删</a></div></div></div></div></div></div></div></div></div></footer> <div class="page-nav"><p class="inner"><span class="prev">
        ←
        <a href="/vue-ebook/vue-ebook/10.html" class="prev">
          第10章 如何正确地进行抽象
        </a></span> <span class="next"><a href="/vue-ebook/vue-ebook/12.html">
          第12章 实战：三天开发一个管理端
        </a>
        →
      </span></p></div>  <div class="gitalk-container theme-default-content"><div id="gitalk-container" class="content"></div></div></main> <div id="kitty-container"><span><div role="tooltip" id="el-popover-3259" aria-hidden="true" class="el-popover el-popper" style="width:undefinedpx;display:none;"><!----><img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/2code2.jpg" class="image"> <div class="text">牡羊猪的猫粮罐</div> </div><span class="el-popover__reference-wrapper"><div id="kitty" style="background:url(https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/assets/img/kitty2.svg);"></div></span></span> <div class="el-dialog__wrapper" style="display:none;"><div role="dialog" aria-modal="true" aria-label="牡羊猪是这样渐渐胖成猪的喵（点击图片可以切换噢）" class="el-dialog" style="margin-top:15vh;"><div class="el-dialog__header"><span class="el-dialog__title">牡羊猪是这样渐渐胖成猪的喵（点击图片可以切换噢）</span><button type="button" aria-label="Close" class="el-dialog__headerbtn"><i class="el-dialog__close el-icon el-icon-close"></i></button></div><!----><!----></div></div></div></div><div class="global-ui"></div></div>
    <script src="/vue-ebook/assets/js/app.a856ee15.js" defer></script><script src="/vue-ebook/assets/js/2.2a4d101b.js" defer></script><script src="/vue-ebook/assets/js/3.9083e877.js" defer></script><script src="/vue-ebook/assets/js/10.adca14b7.js" defer></script>
  </body>
</html>
